import axios from 'axios'
import { toast } from 'vue-sonner'
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: Number(import.meta.env.VITE_API_TIMEOUT)
})

request.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${localStorage.getItem('token') || ''}`
  return config
})

request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 根据不同的错误状态码显示不同的信息
    const status = error.response?.status
    const errorMessage =
      error.response?.data?.message || error.message || '网络请求出现错误'

    let title = '请求失败'
    let description = errorMessage
    let action = {
      label: '重试',
      onClick: () => {
        console.log('重试请求')
      }
    }

    if (status === 401) {
      title = '认证失败'
      description = '登录已过期，请重新登录'
      action = {
        label: '重新登录',
        onClick: () => {
          // 清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
        }
      }
    } else if (status === 403) {
      title = '权限不足'
      description = '您没有权限执行此操作'
      action = {
        label: '联系管理员',
        onClick: () => {
          console.log('联系管理员')
        }
      }
    } else if (status === 404) {
      title = '资源不存在'
      description = '请求的资源不存在'
    } else if (status >= 500) {
      title = '服务器错误'
      description = '服务器内部错误，请稍后重试'
    } else if (typeof window !== 'undefined' && !window.navigator.onLine) {
      title = '网络连接失败'
      description = '请检查您的网络连接'
    }

    toast.error(title, {
      description,
      action,
      duration: 3000 // 3秒后自动消失
    })

    return Promise.reject(error)
  }
)

export default request
